package com.hamilton.erik.pt.mobile.android;

import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.android.volley.Response;
import com.hamilton.erik.pt.core.model.Animal;
import com.hamilton.erik.pt.core.model.Note;
import com.hamilton.erik.pt.mobile.android.volley.response.error.listener.DisplayErrorErrorListener;
import com.hamilton.erik.pt.mobile.client.VolleyJsonRestClient;
import com.hamilton.erik.pt.mobile.util.ResultUtil;

public class ViewNoteActivity extends ViewDataActivity {
	
	private Animal animal = null;
	private Note note = null;
	private String titleNoteType = null;
	private String baseRestPath = null;
	private ProgressDialog progressDialog = null;

	private final int EDIT_ACTIVITY = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_view_note);
		
		findViewById(R.id.note_view_edit_note_button).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						edit();
					}
				});
				
		animal = (Animal)getIntent()
							.getSerializableExtra(
								getString(R.string.extra_animal_object));
		
		titleNoteType = getIntent()
							.getStringExtra(
									getString(R.string.extra_note_title_type));
		
		if(!TextUtils.isEmpty(animal.getName())) {
			StringBuilder titleBuilder = new StringBuilder(animal.getName())
												.append("'s");
			if(titleNoteType != null) {
				titleBuilder.append(" ").append(titleNoteType);
			}
			
			titleBuilder.append(" Note");
			
			setTitle(titleBuilder.toString());
		}
		
		baseRestPath = getIntent().getStringExtra(
							getString(R.string.extra_note_base_rest_path));
		
		retrieve(getIntent());
		populateFields();

	}
	
	protected void retrieve(Intent intent) {
		note = (Note)intent
						.getSerializableExtra(
							getString(R.string.extra_note_object));
	}
	
	protected void populateFields() {
		if(note != null) {
			String temp;
			
			temp = note.getTitle();
			if(!TextUtils.isEmpty(temp)) {
				TextView titleTextView =
					(TextView)findViewById(R.id.note_view_title_field);
				titleTextView.setText(temp);
			}

			temp = note.getDate();
			if(!TextUtils.isEmpty(temp)) {
				TextView dateTextView =
					(TextView)findViewById(R.id.note_view_date_field);
				dateTextView.setText(temp);
			}

			temp = note.getNote();
			if(!TextUtils.isEmpty(temp)) {
				TextView noteTextView =
					(TextView)findViewById(R.id.note_view_note_field);
				noteTextView.setText(temp);
			}
		}
	}
	
	protected void edit() {
		Intent editNoteActivity = new Intent(getApplicationContext(), EditNoteActivity.class);
		editNoteActivity.putExtra(getString(R.string.extra_animal_object), animal);
		editNoteActivity.putExtra(getString(R.string.extra_note_object), note);
		editNoteActivity.putExtra(getString(R.string.extra_note_title_type), titleNoteType);
		editNoteActivity.putExtra(getString(R.string.extra_note_base_rest_path), baseRestPath);
		startActivityForResult(editNoteActivity, EDIT_ACTIVITY);
	}
	
	protected void delete() {
		StringBuilder url = new StringBuilder(baseRestPath);
		url.append("/delete/note/").append(note.getId());
		
		if (progressDialog == null) {
	        progressDialog = new ProgressDialog(this);
	        progressDialog.setTitle(getString(R.string.progress_deleting_title));
	        progressDialog.setMessage(getString(R.string.note_view_progess_deleting_note));
	    }
	    progressDialog.show();
		
		VolleyJsonRestClient.getClient().deleteJsonObject(url.toString(),
								new DeleteNoteSuccessListener(),
								new DisplayErrorErrorListener(this, progressDialog));
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.view_note, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		switch(item.getItemId()) {
			case R.id.action_view_note_edit :
				edit();
				return true;
			case R.id.action_view_note_delete :
				delete();
			default :
				return super.onOptionsItemSelected(item);
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		if(requestCode == EDIT_ACTIVITY && resultCode == ResultUtil.RESULT_SUCCESS) {
			isEdited = true;
			retrieve(data);
			populateFields();
		}
	}
	
	// Catch the back button(After 2.0)
	@Override
	public void onBackPressed() {
		finishWithResult();
	}

	// Catch the back button(Before 2.0)
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if (keyCode == KeyEvent.KEYCODE_BACK) {
			finishWithResult();
	        return true;
	    }
	    return super.onKeyDown(keyCode, event);
	}
	
	public void finishWithResult() {
		if(isEdited) {
			setResult(ResultUtil.EDITED);
		}

		finish();		
	}
	
	private class DeleteNoteSuccessListener implements Response.Listener<JSONObject> {

		@Override
		public void onResponse(JSONObject response) {
			if (progressDialog != null && progressDialog.isShowing()) {
				progressDialog.dismiss();
			}

			setResult(ResultUtil.DELETED, null);
			finish();
		}
	}

}
